from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlmodel import SQLModel, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession

from fastapi import FastAPI

app = FastAPI()


Base = declarative_base()

# DATABASE_URL = "sqlite:///./test.db"
# engine = create_engine(DATABASE_URL)
SQLALCHEMY_DATABASE_URL = "mysql+pymysql://user:password@localhost/mydatabase"

engine = create_engine(
    SQLALCHEMY_DATABASE_URL,
    pool_size=20,
    max_overflow=0,
    pool_pre_ping=True
)

SessionLocal = sessionmaker(
    autocommit=False,
    autoflush=False,
    bind=engine,
    expire_on_commit=False
)


def get_session():
    pass


def get_async_session():
    pass


SQLModel.metadata.create_all(engine)


# 异步会话依赖
async def get_async_session():
    async with AsyncSession(async_engine) as session:
        yield session


# 异步端点示例
@app.get("/heroes/async/", response_model=List[HeroRead])
async def read_heroes_async(session: AsyncSession = Depends(get_async_session)):
    result = await session.execute(select(Hero))
    heroes = result.scalars().all()
    return heroes